﻿using DotNet.Doc;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DotNet.Extensions;
using DotNet.Helper;
using TimeCard.Core;

namespace TimeCard
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        #region 成员变量

        private ApiService Service = new ApiService();

        private int CurrentRowIndex;
        private int CurrentColumnIndex;

        #endregion

        #region 函数

        private void BindYear()
        {
            var beginDate = DateTime.Now.AddMonths(-24).Date;
            var endDate = DateTime.Now.AddMonths(3).Date;

            comboYear.BeginUpdate();
            var currentDate = beginDate;
            while (endDate > currentDate)
            {
                comboYear.Items.Add(currentDate.ToString("yyyy-MM"));
                currentDate = currentDate.AddMonths(1).Date;
            }

            comboYear.EndUpdate();
            comboYear.Text = DateTime.Now.ToString("yyyy-MM");
        }

        private void BindImprotData()
        {
            gridOriginal.DataSource = Service.GetUserOriginalTable();
            gridOriginal.Columns[0].Width = 300;
            gridOriginal.Columns[1].Width = 300;
            gridOriginal.Columns[2].Width = 300;

            gridRule.DataSource = Service.GetUserRuleTable();
            gridRule.Columns[0].Frozen = true;
            gridRule.Columns[1].Frozen = true;
            gridResult.DataSource = null;
            txtReport.Text = null;
        }

        private void BindResultData()
        {
            gridResult.DataSource = Service.GetUserResultTable();
            gridResult.Columns[0].Frozen = true;
            gridResult.Columns[1].Frozen = true;
            txtReport.Text = Service.Model.Report;
        }

        private void ImportCore()
        {
            try
            {
                Service.Import(fileDialog.FileName, comboYear.Text.ToDateTime());
                BindImprotData();
                tabControl1.SelectTab(1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                btnImport.Enabled = true;
                btnImport.Text = "导入";
                btnSubmit.Enabled = true;
                btnSave.Enabled = true;
            }
        }

        private void Import()
        {
            if (InvokeRequired)
            {
                Invoke(new Action(ImportCore));
            }
            else
            {
                ImportCore();
            }
        }

        private void Search()
        {
            btnSearch.Enabled = false;
            btnSearch.Text = "正在查询...";

            Service = new ApiService();

            try
            {
                Service.Search(comboYear.Text.ToDateTime());
                BindImprotData();
                BindResultData();
                tabControl1.SelectTab(1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                btnSearch.Enabled = true;
                btnSearch.Text = "查询";
                btnSubmit.Enabled = true;
                btnSave.Enabled = true;
            }
        }

        private void RuleSetting(Action<string, DataGridViewCell> action)
        {
            if (gridRule.DataSource == null)
            {
                MessageBox.Show("请先导入或者查询数据");
                return;
            }
            var table = (DataTable)gridRule.DataSource;
            //int rowIndex = 0, cellIndex = 0;
            for (int index = 0; index < gridRule.SelectedCells.Count; index++)
            {
                DataGridViewCell cell = gridRule.SelectedCells[index];
                if (cell.ColumnIndex < 2)
                {
                    continue;
                }
                //if (index==0)
                //{
                //    rowIndex = cell.RowIndex;
                //    cellIndex = cell.ColumnIndex;
                //}
                var userName = table.Rows[cell.RowIndex]["姓名"].ToString();
                var day = table.Columns[cell.ColumnIndex].ColumnName;
                var key = Service.GetDicKey(userName, day);
                action(key, cell);
            }
            //gridRule.DataSource = Service.GetUserRuleTable();
            //gridRule.CurrentCell = gridRule.Rows[rowIndex].Cells[cellIndex];

        }

        private void FormatResultCell(DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex < 2)
            {
                return;
            }
            if (e.Value.ToStringOrEmpty().IndexOf("未打卡", StringComparison.Ordinal) > -1)
            {
                e.CellStyle.ForeColor = Color.Red;
            }
            else if (e.Value.ToStringOrEmpty().IndexOf("迟到", StringComparison.Ordinal) > -1
                || e.Value.ToStringOrEmpty().IndexOf("早退", StringComparison.Ordinal) > -1)
            {
                e.CellStyle.BackColor = Color.Yellow;
            }
            else if (e.Value.ToStringOrEmpty().IndexOf("不考勤", StringComparison.Ordinal) > -1)
            {
                e.CellStyle.ForeColor = Color.Gray;
            }
            else
            {
                e.CellStyle.ForeColor = Color.Green;
            }
        }

        #endregion

        private void frmMain_Load(object sender, EventArgs e)
        {
            BindYear();
        }

        private void gridOriginal_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex == 2)
            {
                e.Value = ((DateTime)e.Value).ToString("yyyy-MM-dd HH:mm");
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            Search();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (fileDialog.ShowDialog() != DialogResult.OK) return;
            btnImport.Enabled = false;
            btnImport.Text = "正在导入...";
            ThreadHelper.StartThread(Import, true);
        }

        private void btnMenuSetting_Click(object sender, EventArgs e)
        {
            var frm = new frmSettingRule();
            if (frm.ShowDialog() == DialogResult.OK)
            {
                RuleSetting((key, cell) =>
                {
                    Service.Model.UserRuleDic[key] = frm.SelectedRule;
                    cell.Value = frm.SelectedRule;
                    frm.Dispose();
                });
            }
        }

        private void btnMenuUnSetting_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要清空选定的规则吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) != DialogResult.Yes)
            {
                return;
            }
            RuleSetting((key, cell) =>
            {
                Service.Model.UserRuleDic.Remove(key);
                cell.Value = null;
            });
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            Service.Submit();
            BindResultData();
            tabControl1.SelectTab(2);
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Service.Save();
            MessageBox.Show("保存成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void gridResult_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            FormatResultCell(e);
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (gridRule.DataSource == null)
            {
                e.Cancel = true;
            }
        }

        private void btnRuleManage_Click(object sender, EventArgs e)
        {
            var frm = new frmRuleManage();
            frm.ShowDialog();
            frm.Dispose();
        }

        private void btnMenuWeek_Click(object sender, EventArgs e)
        {
            if (gridRule.DataSource == null)
            {
                MessageBox.Show("请先导入或者查询数据");
                return;
            }
            var table = (DataTable)gridRule.DataSource;
            foreach (DataGridViewRow row in gridRule.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    if (gridRule.Columns[cell.ColumnIndex].HeaderText.IndexOf("星期六", StringComparison.Ordinal)>-1
                        || gridRule.Columns[cell.ColumnIndex].HeaderText.IndexOf("星期日", StringComparison.Ordinal) > -1)
                    {
                        var userName = table.Rows[cell.RowIndex]["姓名"].ToString();
                        var day = table.Columns[cell.ColumnIndex].ColumnName;
                        var key = Service.GetDicKey(userName, day);
                        Service.Model.UserRuleDic.Remove(key);
                        cell.Value = null;
                    }
                }
            }
        }

        private void gridRule_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            //if (e.RowIndex >= 0 && e.Button == MouseButtons.Right)
            //{
            //    gridRule.CurrentCell = gridRule.Rows[e.RowIndex].Cells[e.ColumnIndex];
            //}
            CurrentRowIndex = e.RowIndex;
            CurrentColumnIndex = e.ColumnIndex;
        }

        private void btnMenuSelectedColumn_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in gridRule.Rows)
            {
                row.Cells[CurrentColumnIndex].Selected = true;
            }
        }

        private void gridRule_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = $"{e.Row.Index + 1}";
        }

        
        private void gridResult_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
        {
            e.Row.HeaderCell.Value = $"{e.Row.Index + 1}";
        }
    }
}
